import Regexps from '@/utils/reg';
import { getStringWithoutSpace } from '@/utils/utils';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, history, useModel } from '@umijs/max';
import React, { useMemo, useState } from 'react';
import { useBreakpoint } from '@/hooks/useMediaQuery';
import loginLogo from '../../../../public/black-logo.png';
import {login} from '@/services/ant-design-pro/api';
import './index.less';
import {message} from "antd";
import {flushSync} from "react-dom";

const Login: React.FC = () => {
  const [submitting, setSubmitting] = useState(false);
  const colSize = useBreakpoint();
  const isMobile = useMemo(() => colSize === 'sm' || colSize === 'xs', [colSize]);
  const {initialState, setInitialState} = useModel('@@initialState');
  const [type, setType] = useState<string>('account');
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const handleSubmit = async (values: API.LoginParams) => {
    setSubmitting(true);
    try {
      // 登录
      const msg = await login({
        ...values,
        type,
      });
      if (msg.success === true) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        localStorage.setItem('jwt', msg.data.token || '');
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
	throw new Error(msg.errorMessage);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
	setSubmitting(false);
    }
  };

  return (
    <div className={`main ${isMobile ? 'mobile' : ''}`}>
      <div className="login-logo flex-center">
        <img src={loginLogo} />
        <div className="login-logo-title">
          光环云·算力通平台
        </div>
      </div>
      <div className="flex-center" style={{ height: '100%' }}>
        <div className="login-form-warp">
          <div>
            <div className="text-center login-form-title">
              账号登录
            </div>
            <ProForm<API.LoginParams>
              validateTrigger={['onSubmit']}
              style={{ width: '100%' }}
              submitter={{
                render: (_, dom) => dom.pop(),
                submitButtonProps: {
                  loading: submitting,
                  size: 'large',
                  style: {
                    width: '100%',
                  },
                },
                searchConfig: {
                  submitText: "登录",
                },
              }}
              onFinish={async (values) => {
                // @ts-ignore
                handleSubmit(values);
              }}
            >
              <ProFormText
                fieldProps={{
                  size: 'large',
                  maxLength: 11,
                }}
                label="账号"
                name="account"
                getValueFromEvent={getStringWithoutSpace}
                placeholder={'登录账号'}
                rules={[
                  {
                    required: true,
                    message: '登录账号是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                label="密码"
                name="password"
                fieldProps={{
                  size: 'large',
                }}
                getValueFromEvent={getStringWithoutSpace}
                placeholder={'用户密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
            </ProForm>
          </div>
        </div>
      </div>
      {/* </div> */}
    </div>
  );
};

export default Login;
